const server = require('../../utils/server');
const App = getApp();

Page({
  data: {
    imgType: ['拍照', '相册', '拍照或相册'],
    imgList:[],     // 本地图片链接地址
    dataFiles: [],  // 服务器返回地址
    cookName:'',
    cookDesc:'',
    sortsVal: 0,
    flavorVal: 0,
    iswitch: false,
    isrefre: false,
    sorts: [],
    flavor: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getSorts();
    this.getFlavor();
  },
  getSorts: function () {  //获取菜系分类
    let that = this;
    server.postJSON('getSorts', function (res) {
      if (res.data.status === 200) {
        that.setData({
          sorts: res.data.data
        })
      }
    });
  },
  getFlavor: function () {  //获取口味
    let that = this;
    server.postJSON('getFlavor', function (res) {
      if (res.data.status === 200) {
        that.setData({
          flavor: res.data.data
        })
      }
    });
  },
  openSorts: function () {
    wx.navigateTo({
      url: 'sorts/index',
    })
  },
  openFlavor: function () {
    wx.navigateTo({
      url: 'flavor/index',
    })
  },
  delImage: function(e){
    let oldList = this.data.imgList;
    let oldFiles = this.data.dataFiles;
    oldList.splice(e.currentTarget.dataset.i, 1);
    oldFiles.splice(e.currentTarget.dataset.i,1);
    this.setData({
      imgList: oldList,
      dataFiles: oldFiles
    })
  },
  bindPickerImg: function (e) {
    let that = this;
    App.sourceTypeChange(e.detail.value, 9, function (data) {
      console.log(data)
      that.setData({
        imgList: that.data.imgList.concat(data.tempFiles),
        dataFiles: that.data.dataFiles.concat(data.dataFiles)
      })
    })
  },
  bindPickerSorts: function(e){
    this.setData({
      sortsVal: e.detail.value
    })
  },
  bindPickerFlavor: function (e) {
    this.setData({
      flavorVal: e.detail.value
    })
  },
  saveCase: function(e){
    console.log(e)
    let that = this;
    let data = e.detail.value;
    data.imgs = data.imgs.split(',');
    if (!data.cookName){
      return wx.showToast({
        icon: 'none',
        title: '菜谱名称不能为空',
      })
    }
    server.postJSON('saveCase', data, function (res) {
      if(res.data.status===200){
        wx.showModal({
          title: '温馨提示',
          content: res.data.msg+' 是否继续添加？',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
              that.setData({
                cookName: '',
                cookDesc: '',
                imgList: [],     
                dataFiles: [], 
                sortsVal: 0,
                flavorVal: 0, 
                iswitch: false,
                isrefre: false,
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
              setTimeout(()=>{
                wx.navigateBack()
              },200)
            }
          }
        })
      }
    });
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})